package JavaSE_core.Duo_Thread;

public class Demo4 {

	public static void main(String[] args) {
		Account account = new Account(10000);
		Person husband = new Person("老公", account);
		Person wife = new Person("老婆", account);
		Thread ht = new Thread(husband);
		Thread wt = new Thread(wife);
		ht.start();
		wt.start();

	}

}

class Person implements Runnable {
	private String name;
	private Account account;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}

	public Person() {
	}

	public Person(String name, Account account) {
		super();
		this.name = name;
		this.account = account;
	}

	public void run() {

		// 模拟向银行账户取钱
		/*while (true) {
			synchronized (account) {//同步代码块
				if (account.getMoney() <=0) {
					break;
				}
				try {
					Thread.sleep(5);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				account.setMoney(account.getMoney() - 100);// 取100元
				System.out.println(name + "取出100元，当前账户余额为：" + account.getMoney());
			}
		}*/
		test();
	}
	
	public synchronized void test(){//同步方法
		while (true) {
//			synchronized (account) {//同步代码块
				if (account.getMoney() <=0) {
					break;
				}
				try {
					Thread.sleep(5);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				account.setMoney(account.getMoney() - 100);// 取100元
				System.out.println(name + "取出100元，当前账户余额为：" + account.getMoney());
//			}
		}
	}
}
